import axios from 'axios'
import { checkStatus } from './checkStatus'
import { addPending, removePending } from '@/axios/tool/cancelRequest'

export const createAxiosInterceptor = http => {
  // 请求拦截
  http.interceptors.request.use(config => {
    removePending(config) // 在请求开始前，对之前的请求做检查取消操作
    addPending(config) // 将当前请求添加到 pending 中
    const token = localStorage.getItem('token') || null
    token ? config.headers['Authorization'] = token : ''
    return config
  }, undefined)

  // 响应拦截
  http.interceptors.response.use(response => {
    removePending(response)
    const { data } = response || {}
    const code = data.code || data.statusCode || null
    code && code !== 200 && (data.msg || data.message) ? checkStatus(code, data.msg || data.message) : ''
    return data
  }, error => {
    let { response, code , message } = error || {}
    console.log(response);
    const err = error.toString()
    try {
      if (code === 'ECONNABORTED' && message.indexOf('timeout') !== -1) {
        $message.error('接口请求超时，请刷新页面重试!')
        return
      }
      if (err && err.includes('Network Error')) {
        $message.error('网络异常，请检查网络连接是否正常!')
        return Promise.reject(error)
      }
    } catch (e) {
      throw new Error(e)
    }
    // 请求是否被取消
    const isCancel = axios.isCancel(error)
    const status = response?.code || response?.status || response?.statusCode || response?.data?.statusCode
    const msg = response?.message || response?.data?.msg || response?.data?.message
    !isCancel ? checkStatus(status, msg) : ''
    return Promise.reject(response?.data)
  })
}
